/**
 * AJAX全局设置
 */
$.ajaxSetup({
    type: "post",
    dataType: "json"
});

/**
 * 方法集合
 */
var HS = HS || {};

HS.U = function(url,param){
    let connect = '',params = '';
    if(!$.isEmptyObject(param)){
        connect = url.indexOf('?')>-1?'&':'?';
        $.each(param,function (k, v) {
            params += k + '=' + v + '&';
        });
        connect = connect + params.substring(0,params.length-1)
    }
    return url + connect;
};

HS.getParams = function (obj) {
    let params = {};
    $(obj).each(function(){
        params[$(this).attr('name')] = $.trim($(this).val());
    });
    return params;
};

$('.layui-upload').click(function(){
    let index = $('.layui-upload').index(this);
    layui.data('_img_url', {
        key: 'index',value: index
    });
});
//设备信息
var device = layui.device();
/**
 * layui加载模块
 */
layui.use(['layer', 'element', 'form', 'upload', 'laydate'], function(){  //如果只加载一个模块，可以不填数组。如：layui.use('form')
    var layer = layui.layer,
        element = layui.element,
        form = layui.form,  //获取form模块
        upload = layui.upload,
        laydate = layui.laydate;

    /**
     * 通用单图上传
     */
    upload.render({
        elem: '._img_url',
        url: '/admin/hsjson/upload',
        //accept: 'file',   //默认images
        acceptMime: 'image/*',//只显示图片文件,参数为 layui 2.2.6 开始新增
        exts: 'jpg|png|gif|bmp|jpeg',
        before: function(obj){ //obj参数包含的信息，跟 choose回调完全一致，可参见上文。
            layer.msg('上传中···',{time:60000,icon: 16,shade: 0.3});
        },
        done: function(res){
            //如果上传失败
            if(res.error > 0){
                return layer.msg(res.message);
            }
            //上传成功
            if (device.ie===8 || device.ie===9){//ie8、9浏览器无法获取item
                let item = $('.layui-upload').eq(layui.data('_img_url').index);
                item.children("input").val(res.url);
                item.children('img').attr('src', res.url); //图片链接
            }else{
                //获取当前触发上传的元素，一般用于 elem 绑定 class 的情况，注意：此乃 layui 2.1.0 新增
                let item = this.item;
                item.prev("input").val(res.url);
                item.next().next('img').attr('src', res.url); //图片链接
            }
            layer.closeAll();
        }
    });

    //自定义验证规则
    form.verify({
        /*title: function(value){
            if(value.length < 5){
            return '标题至少得5个字符啊';
            }
        },*/
        //pass: [/(.+){6,20}$/, '密码必须6到20位']
        pass:[/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$/,'密码必须同时包含数字和字母且长度在8-16位']
    });
    /**
     * 通用表单提交(AJAX方式)
     */
    form.on('submit(*)', function (data) {
        let loading = layer.load(0); //0代表加载的风格，支持0-2
        if(editor){
            editor.sync();//将编辑器的HTML数据同步到textarea
            if(editor2){editor2.sync();if(editor3){editor3.sync();}}
        }
        /*var form_data = data.field;//$(data.form).serialize()
        form_data.copy_nid = $('#copy_nid').val()
        delete form_data.file;//使用data.field，会生成file的键，删除*/
        $.ajax({
            url: data.form.action,
            type: data.form.method,
            data: $(data.form).serialize(),
            success: function (info) {
                if (info.code === 1) {
                    setTimeout(function () {
                        layer.close(loading); //关闭加载层
                        location.href = info.url;
                    }, 1000);
                }

                setTimeout(function () {
                    layer.close(loading); //关闭加载层
                    layer.msg(info.msg);
                }, 1000);
            }
        });
        return false;
    });
    //监听select后进行搜索
    form.on('select(ss)', function(data){
        $('#ss').submit();
    });
    /**
     * 通用批量处理（审核、取消审核、删除）
     */
    $('.ajax-action').on('click', function () {
        let _action = $(this).data('action');
        layer.open({
            shade: false,
            content: '确定执行此操作？',
            btn: ['确定', '取消'],
            yes: function (index) {
                let loading = layer.load(0, {shade: false}); //0代表加载的风格，支持0-2
                $.ajax({
                    url: _action,
                    data: $('.ajax-form').serialize(),
                    success: function (info) {
                        layer.close(loading);
                        if (info.code === 1) {
                            setTimeout(function () {
                                location.href = info.url;
                            }, 1000);
                        }
                        layer.msg(info.msg);
                    }
                });
                layer.close(index);
            }
        });

        return false;
    });
    /**
     * 通用删除
     */
    $('.ajax-delete').on('click', function () {
        let _href = $(this).attr('href');
        layer.open({
            shade: false,
            content: '确定删除？',
            btn: ['确定', '取消'],
            yes: function (index) {
                let loading = layer.load(0, {shade: false}); //0代表加载的风格，支持0-2
                $.ajax({
                    url: _href,
                    type: "get",
                    success: function (info) {
                        layer.close(loading);
                        if (info.code === 1) {
                            setTimeout(function () {
                                location.href = info.url;
                            }, 1000);
                        }
                        layer.msg(info.msg);
                    }
                });
                layer.close(index);
            }
        });
        return false;
    });
    /**
     * 通用确认后跳转
     */
    $('.href-confim').on('click', function () {
        let _href = $(this).attr('href');
        let msg   = $(this).attr('msg');
        let _msg  = msg?msg:'确认跳转？';
        layer.open({
            shade: false,
            content:_msg,
            btn: ['确定', '取消'],
            yes: function (index) {
                let loading = layer.load(0, {shade: false}); //0代表加载的风格，支持0-2
                location.href = _href;
                layer.close(loading);
                layer.close(index);
            }
        });
        return false;
    });
    /**
     * 通用确认操作后执行
     */
    $('.ajax-confim').on('click', function () {
        let _href = $(this).attr('href');
        let _data = $(this).attr('data-param');
        layer.open({
            shade: false,
            content: '确认操作？',
            btn: ['确定', '取消'],
            yes: function (index) {
                let loading = layer.load(0, {shade: false}); //0代表加载的风格，支持0-2
                $.ajax({
                    url: _href,
                    type: "post",
                    data: _data,
                    success: function (info) {
                        layer.close(loading);
                        if (info.code === 1) {
                            setTimeout(function () {
                                location.href = info.url;
                            }, 1000);
                        }
                        layer.msg(info.msg);
                    }
                });
                layer.close(index);
            }
        });
        return false;
    });
    /**
     * 通用get - ajax提交
     */
    $('.ajax-get').on('click', function () {
        let _href = $(this).attr('href');
        let _data = $(this).attr('data-param');
        let loading = layer.load(0, {shade: false}); //0代表加载的风格，支持0-2
        $.ajax({
            url: _href,
            type: "get",
            data: _data,
            success: function (info) {
                layer.close(loading);
                if (info.code === 1) {
                    setTimeout(function () {
                        location.href = info.url;
                    }, 1000);
                }
                layer.msg(info.msg);
            }
        });
        return false;
    });
    /**
     * 通用post - ajax提交
     */
    $('.ajax-post').on('click', function () {
        let _href = $(this).attr('href');
        let _data = $(this).attr('data-param');
        let loading = layer.load(0, {shade: false}); //0代表加载的风格，支持0-2
        $.ajax({
            url: _href,
            type: "post",
            data: _data,
            success: function (info) {
                layer.close(loading);
                if (info.code === 1) {
                    setTimeout(function () {
                        location.href = info.url;
                    }, 1000);
                }
                layer.msg(info.msg);
            }
        });
        return false;
    });
    /**
     * 通用日期时间选择
     */
    laydate.render({
        elem: '.datetime'
        ,type: 'datetime'   //年月日时间
    });
    //同时绑定多个,年月日
    lay('.date').each(function(){
        laydate.render({
            elem: this,
            type: 'date'
            ,trigger: 'click'
        });
    });
    //选择省，获取市信息，清空县信息
    form.on('select(pid)', function(data){
        $.post(HS.U('/admin/Webindex/getCity'),{pid:data.value},function (data) {
            if(!$.isEmptyObject(data)){
                let html = '<option value="">请选择市</option>';
                $.each(data,function (k, v) {
                    html += '<option value="'+k+'">'+v+'</option>';
                });
                $('select[name="cid"]').html(html);
                $('select[name="aid"]').html('<option value="">请选择区/县</option>');
                form.render('select');
            }
        })
    });
    //选择市，
    form.on('select(cid)', function(data){
        $.post(HS.U('/admin/Webindex/getCity'),{pid:data.value},function (data) {
            if(!$.isEmptyObject(data)){
                let html = '<option value="">请选择区/县</option>';
                $.each(data,function (k, v) {
                    html += '<option value="'+k+'">'+v+'</option>';
                });
                $('select[name="aid"]').html(html);
                form.render('select');
            }
        })
    });
});


/**
 * 通用全选
 */
$('.check-all').on('click', function () {
    $(this).parents('table').find('input[type="checkbox"]').prop('checked', $(this).prop('checked'));
});

/**
 * 多图上传
 */
function upload_imglist(elem){
    elem=elem||'imgList';
    layui.use('upload', function(){
        let upload = layui.upload;
        //多图片上传
        upload.render({
            elem: '#'+elem,
            url: '/admin/hsjson/upload',
            acceptMime: 'image/*',//只显示图片文件,参数为 layui 2.2.6 开始新增
            exts: 'jpg|png|gif|bmp|jpeg',
            multiple: true,
            done: function(res){
                //如果上传失败
                if(res.error > 0){
                    return layer.msg(res.message);
                }
                //上传完毕
                let html = '<div class="photo-list"><input type="text" name="tit_'+elem+'[]" value="" placeholder="标题" maxlength="100" autocomplete="off" class="layui-input layui-input-inline">' +
                    '<input type="text" name="photo_'+elem+'[]" value="' + res.url + '" class="layui-input layui-input-inline">'+
                    '<input type="text" name="sort_'+elem+'[]" value="0" maxlength="10" title="数字大的在前" style="width: 50px;" class="layui-input layui-input-inline">'+
                    '<button type="button" class="layui-btn layui-btn-danger remove-photo-btn">移除</button>'+
                    '&nbsp;<img src="'+ res.url +'" height="38" class="layui-upload-img"></div>';
                $('#photo-container_'+elem).append(html).on('click', '.remove-photo-btn', function () {
                    $(this).parent('.photo-list').remove();
                });
            }
        });
    });
    $('#photo-container_'+elem).on('click', '.remove-photo-btn', function () {
        $(this).parent('.photo-list').remove();
    });
}
/*多语言切换及内容显示*/
$(function () {
    $('div[class^="list_"]:not(".list_0")').hide();
    $(".language-btn ul li").on("click",function () {
        $(this).removeClass("layui-btn-primary").siblings().addClass("layui-btn-primary");
        $('div[class^="list_"]').hide();//注意div多个class时，list_必须放在第一个
        $('div .list_'+$(this).index()).show();
    })
});
/*页面选取中文图片功能*/
function copy_img(name,obj) {
    let img_url = $("input[name='"+name+"']").val();
    if(!img_url)return layer.msg('请先上传中文图片');
    $(obj).siblings("input:eq(0)").val(img_url);
    $(obj).prev('img').attr('src',img_url)
}